// background.js

function isAudioMimeType(mimeType) {
  return mimeType.startsWith("audio/");
}

chrome.webRequest.onHeadersReceived.addListener(
  (details) => {
    // console.log("----", details);
    const audioHeader = details.responseHeaders.find((header) => {
      return (
        header.name.toLowerCase() === "content-type" &&
        isAudioMimeType(header.value.toLowerCase())
      );
    });

    if (audioHeader) {
      const audioUrl = details.url;

      // 向当前活动的标签页发送消息
      chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (tabs[0]) {
          chrome.tabs.sendMessage(tabs[0].id, {
            type: "audioUrl",
            audioUrl: audioUrl,
          });
        }
      });
    }
  },
  { urls: ["https://*.ximalaya.com/*", "https://*.xmcdn.com/*"] },
  ["responseHeaders"]
);
